
//
//  lookForCarViewController.m
//  autoHome
//
//  Created by qianfeng on 15/9/9.
//  Copyright (c) 2015年 qf1523. All rights reserved.
//

#import "lookForCarViewController.h"
#import <MapKit/MapKit.h>
#import "XXRequest.h"
#import "ParkModel.h"
#import "IATConfig.h"

#define URL @"http://restapi.amap.com/v3/place/around?key=3580ebb3206c02633aa55651fd464d79&keywords=停车场&location=%f,%f&radius=1000"
@interface lookForCarViewController ()<MKMapViewDelegate,CLLocationManagerDelegate,IFlyRecognizerViewDelegate>
{
    MKMapView *_mapView;
    
    //定位管理器
    CLLocationManager *_manager;
    
    NSMutableArray *_dataArr;
    
    CLLocation *_location;
    
    UITextField *_locationName;
    
    IFlyRecognizerView      *_iflyRecognizerView;

}
@end

@implementation lookForCarViewController

- (void)viewDidLoad {

    [super viewDidLoad];
    
  
    
    _dataArr = [NSMutableArray array];
    [self creatMapView];

    [self creatNavBar];
}
-(void)creatNavBar
{
    self.navigationController.navigationBarHidden = YES;
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 64)];
    //    headView.backgroundColor = [UIColor cyanColor];
   
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.titleLabel.font = [UIFont systemFontOfSize:15];
        btn.tag = 11;
                [btn addTarget:self action:@selector(showMyLo) forControlEvents:UIControlEventTouchUpInside];
        btn.frame = CGRectMake(10, 24, 30, 30);
        [btn setImage:[UIImage imageNamed:@"main_zoomwidget_locate@2x.png"] forState:UIControlStateNormal];
        [headView addSubview:btn];
    
  
    
        UIButton *rBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [rBtn setFrame:CGRectMake(self.view.bounds.size.width-30, 24, 25, 25)];
        [rBtn setBackgroundImage:[UIImage imageNamed:@"searchBar_search@2x"] forState:UIControlStateNormal];
        ;
    
    
    [self.view bringSubviewToFront:headView];
    
    headView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:headView];
    
    _locationName = [[UITextField alloc] initWithFrame:CGRectMake(50, 24, self.view.frame.size.width - 140, 30)];
    _locationName.borderStyle = UITextBorderStyleRoundedRect;
    [headView addSubview:_locationName];
//    UIButton *voidBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [voidBtn setFrame:CGRectMake(0, 0, 30, 30)];
//    [voidBtn setImage:[UIImage imageNamed:@"feedback@2x.png"] forState:UIControlStateNormal];
//    
//    [voidBtn addTarget:self action:@selector(say:) forControlEvents:UIControlEventTouchUpInside];
//    _locationName.rightViewMode = UITextFieldViewModeAlways;
//    
//    _locationName.rightView = voidBtn;
    UIButton *voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    voiceBtn.frame = CGRectMake(self.view.frame.size.width - 90, 24, 30, 30);
    [voiceBtn setImage:[UIImage imageNamed:@"feedback@2x.png"] forState:UIControlStateNormal];
    [voiceBtn addTarget:self action:@selector(say:) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:voiceBtn];
    
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    searchBtn.frame = CGRectMake(self.view.frame.size.width - 60, 24, 40, 30);
    [searchBtn setTitle:@"搜索" forState:UIControlStateNormal];
    [searchBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(searchBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:searchBtn];
    
}
-(void)searchBtnClick
{

    if (_locationName.text.length == 0) {
        return;
    }
   
    [self locationCallBack:_locationName.text];
    

    
}
 //反地理编码
-(void)locationCallBack:(NSString *)cityName
{

    CLGeocoder *geo = [[CLGeocoder alloc] init];
    
    //
    [geo geocodeAddressString:cityName completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *place = [placemarks firstObject];
        
        if (error||placemarks.count==0) {
                _locationName.text=[NSString stringWithFormat:@"%@ 😢%@",_locationName.text,@"你是要去火星吗？"];
            return ;
            }
        
        [self showParkByLocation:place.location];
        }];

}

-(void)say:(UIButton*)btn
{
    _locationName.text = @"";
    NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@",@"560a52b5"];
    [IFlySpeechUtility createUtility:initString];
    //初始化语音识别控件
    
   
    
    //单例模式，UI的实例
    if (_iflyRecognizerView == nil) {
        //UI显示剧中
        _iflyRecognizerView= [[IFlyRecognizerView alloc] initWithCenter:self.view.center];
        
        [_iflyRecognizerView setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        
        //设置听写模式
        [_iflyRecognizerView setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
        
    }
    _iflyRecognizerView.delegate = self;
    
    if (_iflyRecognizerView != nil) {
        IATConfig *instance = [IATConfig sharedInstance];
        //设置最长录音时间
        [_iflyRecognizerView setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
        //设置后端点
        [_iflyRecognizerView setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
        //设置前端点
        [_iflyRecognizerView setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
        //网络等待时间
        [_iflyRecognizerView setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];
        
        //设置采样率，推荐使用16K
        [_iflyRecognizerView setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
        if ([instance.language isEqualToString:[IATConfig chinese]]) {
            //设置语言
            [_iflyRecognizerView setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
            //设置方言
            [_iflyRecognizerView setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
        }else if ([instance.language isEqualToString:[IATConfig english]]) {
            //设置语言
            [_iflyRecognizerView setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
        }
        //设置是否返回标点符号
//        [_iflyRecognizerView setParameter:nil forKey:[IFlySpeechConstant ASR_PTT]];
        
    }
//    [_iflyRecognizerView setParameter: @"sms" forKey: [IFlySpeechConstant IFLY_DOMAIN]];
  
    
    //设置听写结果格式为json
    [_iflyRecognizerView setParameter:@"plain" forKey:[IFlySpeechConstant RESULT_TYPE]];
    
    //保存录音文件，保存在sdk工作路径中，如未设置工作路径，则默认保存在library/cache下
    [_iflyRecognizerView setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
    
    [_iflyRecognizerView start];
    


}

-(void)viewWillDisappear:(BOOL)animated
{
    [_iflyRecognizerView cancel]; //取消识别
    [_iflyRecognizerView setDelegate:nil];
    [_iflyRecognizerView setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
    
    
}
- (void)onResult: (NSArray *)resultArray isLast:(BOOL) isLast
{
    NSLog(@"~~~~%@",resultArray);
    NSMutableString *result = [[NSMutableString alloc] init];
    NSDictionary *dic = [resultArray objectAtIndex:0];
    
    for (NSString *key in dic) {
        [result appendFormat:@"%@",key];
    }
    _locationName.text = [[[NSString stringWithFormat:@"%@%@",_locationName.text,result] componentsSeparatedByString:@"。"] firstObject];
    
    
    [self locationCallBack:_locationName.text];
}

- (void)onError: (IFlySpeechError *) error
{
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_locationName resignFirstResponder];
}

-(void)creatMapView
{
    _mapView =  [[MKMapView alloc] initWithFrame:self.view.frame];
    _mapView.delegate = self;
    [self.view addSubview:_mapView];
    


    //显示自己位置
    _mapView.showsUserLocation = YES;
    
    _manager = [[CLLocationManager alloc] init];
    _manager.delegate =self;
    
    //下面2个方法没实现 系统会提示
    [_manager requestAlwaysAuthorization];
    [_manager requestWhenInUseAuthorization];

    //在plist中添加2个值NSLocationWhenInUseUsageDescription  NSLocationAlwaysUsageDescription  都是布尔值  YES
    
    
    [_manager startUpdatingLocation];
    _manager.distanceFilter = 1000.0;

    
    
        //设置经纬度
        CLLocationCoordinate2D coor = CLLocationCoordinate2DMake(_manager.location.coordinate.latitude,_manager.location.coordinate.longitude);
    NSLog(@"%f",coor.latitude);
    
    //设置放大系数
        MKCoordinateSpan span = MKCoordinateSpanMake(0.01f, 0.01f);
    
        //组成结构体
    
        MKCoordinateRegion region = MKCoordinateRegionMake(coor, span);
    
        [_mapView setRegion:region];
    
    
    UILongPressGestureRecognizer *_longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    
    [_mapView addGestureRecognizer:_longPress];
    
    
    //逆地理编码
    
    
   

    
}

-(void)showMyLo
{
    [UIView animateWithDuration:0.2 animations:^{
        [_mapView setRegion:MKCoordinateRegionMake(_location.coordinate, MKCoordinateSpanMake(0.01f, 0.01f))];
    }];
    [_manager startUpdatingLocation];
}

#pragma mark - 地图代理

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{

    //读取到最新的定位数据
    CLLocation *newLocation = [locations lastObject];
    NSLog(@"%@",newLocation);
    //移动地图
    _location = newLocation;
     [UIView animateWithDuration:1 animations:^{
    [_mapView setRegion:MKCoordinateRegionMake(newLocation.coordinate, MKCoordinateSpanMake(0.01f, 0.01f))];
     }];
    [self showParkByLocation:newLocation];
    
//    NSLog(@"%f~~%f",newLocation.coordinate.latitude,newLocation.coordinate.longitude);
//    //反地理编码
//    CLGeocoder *geo = [[CLGeocoder alloc] init];
//    [geo reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
//       
//        CLPlacemark *place = [placemarks firstObject];
//        NSLog(@"%@",place.addressDictionary);
//
//        NSData*data=[NSJSONSerialization dataWithJSONObject:place.addressDictionary options:NSJSONWritingPrettyPrinted error:nil];
//        NSString*str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//        
//        NSLog(@"%@",str);
//        
//        
//    }];
}


//通过位置来进行请求
-(void)showParkByLocation:(CLLocation*)location
{
    
    [UIView animateWithDuration:0.2 animations:^{
        [_mapView setRegion:MKCoordinateRegionMake(location.coordinate, MKCoordinateSpanMake(0.01f, 0.01f))];
    }];
    
    NSString *path =[NSString stringWithFormat:URL,location.coordinate.longitude,location.coordinate.latitude];
    
    //防止链接有中文出错
    NSString *urlStr = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    [_dataArr removeAllObjects];
    XXRequest *request = [[XXRequest alloc] init];
    
    [request starGetRequestWithUrl:urlStr andSuccessCode:^(id result) {
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSArray *poisArr = result[@"pois"];
            for (NSDictionary *dic in poisArr) {
                ParkModel *model = [[ParkModel alloc] init];
                
                [model setValuesForKeysWithDictionary:dic];
                
                [_dataArr addObject:model];
            }
            [self showPark:_dataArr];
        }
        
        
    }];

    
}

-(void)showPark:(NSArray *)array
{
    [_mapView removeAnnotations:_mapView.annotations];

        for( ParkModel *model in array){
        NSLog(@"%@",model.location);
        NSArray *arr = [model.location componentsSeparatedByString:@","];
        

        
        CLLocationCoordinate2D coor = CLLocationCoordinate2DMake([arr[1] floatValue],[arr[0] floatValue]);
        MKPointAnnotation *annotation = [[MKPointAnnotation alloc]init];
        
        annotation.coordinate = coor;
        
        annotation.title = [NSString stringWithFormat:@"%@",model.name];
        
        annotation.subtitle = [NSString stringWithFormat:@"距离中心位置%@米",model.distance];
        
        [_mapView addAnnotation:annotation];
    }
    
    
    
}

-(void)longPress:(UILongPressGestureRecognizer*)press
{

    
    if (press.state != UIGestureRecognizerStateBegan ) {
        return;
    }
    
    CGPoint point = [press locationInView:press.view];
//    _mapView.center = point;
    CLLocationCoordinate2D coor = [_mapView convertPoint:point toCoordinateFromView:_mapView];
    
    CLLocation *location = [[CLLocation alloc] initWithLatitude:coor.latitude longitude:coor.longitude];
    
    [self showParkByLocation:location];
}




-(MKAnnotationView*)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    MKAnnotationView *annot = [mapView dequeueReusableAnnotationViewWithIdentifier:@"PARK"];
    if (!annot) {
        annot = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"PARK"];
    }
    
    annot.image = [UIImage imageNamed:@"viorank_pin_parking_pressed@2x.png"];
    annot.frame = CGRectMake(0, 0, 20, 30);
    [UIView animateWithDuration:0.5 animations:^{
        annot.frame = CGRectMake(0, 0, 30, 45);
        
    }];
    
    annot.canShowCallout = YES;
    
    return annot;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

////使用原生的大头÷针
//-(MKAnnotationView*)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
//{
//    //和tableView的复用是一样
//    
//    //MKPinAnnotationView继承于MKAnnotationView的方法一个扩展
//    MKPinAnnotationView*pinAnnotation=(MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:@"ID"];
//     pinAnnotation=[[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"ID"];
////    if (!pinAnnotation) {
////        pinAnnotation=[[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"ID"];
////    }
//    //设置大头针的颜色
//    //pinAnnotation.pinColor=MKPinAnnotationColorGreen;
//    pinAnnotation.pinColor=arc4random()%3;
//    //设置掉下来的动画
//    pinAnnotation.animatesDrop=YES;
//    //显示气泡
//    pinAnnotation.canShowCallout=YES;
//    //设置左边的头像
//    UIImageView*leftImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
//    leftImageView.image=[UIImage imageNamed:@"viorank_pin_parking_pressed@2x.png"];
//    leftImageView.layer.cornerRadius=15;
//    leftImageView.layer.masksToBounds=YES;
//    pinAnnotation.leftCalloutAccessoryView=leftImageView;
//    //设置右边的详情
//    UIButton*rightButton=[UIButton buttonWithType:UIButtonTypeInfoDark];
//    [rightButton addTarget:self action:@selector(rightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
//    pinAnnotation.rightCalloutAccessoryView=rightButton;
//    
//    return pinAnnotation;
//}
//-(void)rightButtonClick:(UIButton*)button{
//    
//    NSLog(@"地图大头针按钮");
//}

@end
